package cn.jbolt.ec.task;

import cn.jbolt.common.model.BecMember;
import cn.jbolt.common.model.BecMemberCoupon;
import cn.jbolt.common.model.BecRetailerMemberBalance;
import cn.jbolt.common.model.BecRetailerOrder;
import cn.jbolt.ec.order.OrderService;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;

import com.jfinal.log.Log;
import java.util.List;

public class OrderSchedule implements Runnable {
    private static Log log = Log.getLog(OrderSchedule.class);
    @Override
    public void run() {
        order_close();
        log.info("Another minute ticked away...");
    }

    @Inject
    OrderService orderService;

    public void order_close(){
        //172800000
        Kv cond=Kv.by("type<=",3).set("status<=",6).set("order_time<",System.currentTimeMillis()-172800000);
        List<BecRetailerOrder> list= OrderService.me.getCommonList("*",cond,true);
        for (BecRetailerOrder becRetailerOrder : list) {
            BecMember member1=new BecMember();
            BecMember member= member1.findById(becRetailerOrder.getClientId());
            if (null!=member){

                if (null!=becRetailerOrder.getCouponId()){
                    BecMemberCoupon becMemberCoupon=new BecMemberCoupon().dao().findById(becRetailerOrder.getCouponId());
                    becMemberCoupon.setUsed(false);
                    becMemberCoupon.update();
                }

                if (becRetailerOrder.getBonusAmount()>0||becRetailerOrder.getRetailerBalanceAmount()>0){
                    BecRetailerMemberBalance becRetailerMemberBalance=new BecRetailerMemberBalance().dao().
                            findFirst("select * from bec_retailer_member_balance where member_id=? and retailer_id=?",becRetailerOrder.getClientId(),becRetailerOrder.getRetailerId());
                    becRetailerMemberBalance.setChargeBonus(becRetailerMemberBalance.getChargeBonus()+becRetailerOrder.getBonusAmount());
                    becRetailerMemberBalance.setBalance(becRetailerMemberBalance.getBalance()+becRetailerOrder.getRetailerBalanceAmount());
                    becRetailerMemberBalance.update();
                }

                if (becRetailerOrder.getBalanceAmount()>0){
                    BecMember becMember=new BecMember().dao().findById(becRetailerOrder.getClientId());

                    if (becMember.getBalance()>0){
                        becMember.setBalance(becMember.getBalance()+becRetailerOrder.getBalanceAmount());
                    }else{
                        becMember.setBalance((long)becRetailerOrder.getBalanceAmount());
                    }
                    becMember.update();

                }
                BecRetailerOrder retailerOrder=new BecRetailerOrder().dao().findById(becRetailerOrder.getId());
                retailerOrder.setStatus(20);
                retailerOrder.update();

            }else {

            }
        }
    }
}